package top.hcode.hoj.utils;

import org.nutz.json.Json;
import org.nutz.lang.Lang;
import org.nutz.lang.Strings;
import org.nutz.lang.util.NutMap;

import java.net.HttpCookie;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author orangej
 * @since 2024/12/15
 */
public class CookiesUtils {

    public static List<HttpCookie> parseCookiesJson(String cookiesJson) {
        List<HttpCookie> cookies = new ArrayList<>();
        if (Strings.isNotBlank(cookiesJson)) {
            NutMap map = Json.fromJson(NutMap.class, cookiesJson);
            for (String key : map.keySet()) {
                String value = map.getString(key);
                cookies.add(new HttpCookie(key, value));
            }
        }

        return cookies;
    }

    public static Map<String, String> toMap(List<HttpCookie> cookies) {
        if (Lang.isEmpty(cookies)) {
            return new HashMap<>();
        }

        return cookies.stream().collect(Collectors.toMap(HttpCookie::getName, HttpCookie::getValue));
    }
}
